package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.health.dao.OrderDao;
import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.exception.DuplicateOperateException;
import com.itheima.health.exception.OrderCountOverLimitExceptoin;
import com.itheima.health.exception.OrderTimeNotAllowedException;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderService;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderService.class)
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderSettingDao orderSettingDao;
    @Transactional
    @Override
    public Order add(Order order) throws OrderCountOverLimitExceptoin, DuplicateOperateException, OrderTimeNotAllowedException {
        log.info("[预约设置-添加]data:{}",order);
        //没设置 ordersetting
        OrderSetting orderSetting=orderSettingDao.selectByOrderDate(order.getOrderDate());
        if (null==orderSetting){
            //如果不存在，不能预约
            throw new OrderTimeNotAllowedException("该时间不能进行预约！");
        }else if (orderSetting.getNumber()<=orderSetting.getReservations()){
            //预约满
            throw new OrderCountOverLimitExceptoin("已约满");
        }

        //重复
        long count=orderDao.countByMemberAndDateAndSetMeal(order.getMemberId(),order.getOrderDate(),order.getSetmealId());
        if (count>0){
            throw new DuplicateOperateException("重复预约");
        }
        //数据入库
        orderDao.insert(order);
        //更新 reservations
        orderSettingDao.updateReservationsById(orderSetting.getReservations()+1,orderSetting.getId());


        return orderDao.selectById(order.getId());
    }

    @Transactional
    @Override
    public Order findById(Integer id) {
        return orderDao.selectById(id);
    }

    @Override
    public List<Map<String, Object>> countBySetmeal() {
        return orderDao.countBySetmeal();
    }
}
